package com.hhkj.api.sale.common.component.manager;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.hhkj.admin.sale.common.cont.SaleConst;
import com.hhkj.admin.sale.domain.Sale;
import com.hhkj.admin.sale.service.base.SaleService;
import com.hhkj.api.common.service.biz.base.SalePasswordService;
import com.hhkj.api.sale.common.session.holder.ApiSaleSessionHolder;
import com.hhkj.api.sale.common.session.model.LoginSale;
import com.hhkj.api.sale.model.req.ApiSaleLoginReq;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.exception.GlobalException;
import com.ruoyi.common.exception.user.UserPasswordNotMatchException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.framework.login.api.ApiSessionConst;
import com.ruoyi.framework.login.api.ApiSessionUtils;
import com.ruoyi.framework.security.context.AuthenticationContextHolder;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * ApiSaleLoginManager
 *
 * @author HHKJ-SERVER-ZJ
 * @since 2023/10/26 8:35
 */
@Component
public class ApiSaleLoginManager {

    @Autowired
    private SaleService saleService;
    @Autowired
    private RedisCache redisCache;
    @Autowired
    private ISysUserService userService;
    @Resource(name = "salePasswordService")
    private SalePasswordService salePasswordService;

    /**
     * 登出接口
     *
     * @return true/false
     */
    public boolean doLoginOut() {
        LoginSale loginSale = ApiSaleSessionHolder.getLoginSale();
        String cacheKeyPrefix = ApiSessionUtils.createCacheKeyPrefix(LoginSale.class, loginSale.getId().toString());
        // 清除已登录的商家
        redisCache.deleteBatchObject(cacheKeyPrefix);
        return true;
    }

    /**
     * 登录
     *
     * @param req 请求信息
     * @return 用户登录信息
     */
    public LoginSale doLogin(ApiSaleLoginReq req) {
        String thirdSessionKey = UUID.randomUUID().toString();
        Sale salePo = saleService.getByMobile(req.getMobile());
        if (ObjectUtil.isEmpty(salePo)) {
            throw new UserPasswordNotMatchException();
        }
        if (SaleConst.DisabledFlag.YES.getCode().equals(salePo.getDisabledFlag())) {
            throw new GlobalException("商家已被禁用");
        }
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(req.getMobile(), req.getPassword());
        AuthenticationContextHolder.setContext(authenticationToken);
        salePasswordService.validate(salePo.getPassword());
        LoginSale loginSale = BeanUtil.toBean(salePo, LoginSale.class);
        // 创建键
        String sessionKey = ApiSessionUtils.createSessionKey(loginSale.getId().toString(), thirdSessionKey);
        loginSale.setSessionKey(sessionKey);
        String cacheKey = ApiSessionUtils.createCacheKey(LoginSale.class, sessionKey);
        String cacheKeyPrefix = ApiSessionUtils.createCacheKeyPrefix(LoginSale.class, loginSale.getId().toString());
        // 获取默认企业
        SysUser defaultUser = userService.getDefaultUser();
        if (ObjectUtil.isNull(defaultUser)) {
            throw new GlobalException("系统默认机构未配置，请联系管理员！");
        }
        loginSale.setDefaultCreateBy(defaultUser.getUserId());
        // 清除已登录的商家
        redisCache.deleteBatchObject(cacheKeyPrefix);
        redisCache.setCacheObject(cacheKey, loginSale, ApiSessionConst.SESSION_TIME_OUT, TimeUnit.HOURS);
        return loginSale;
    }
}
